import { useEffect, useState } from "react";
import { View } from "@tarojs/components";
import {
  Layout,
  WithMargins,
  C06HeroSlideBanner,
  C07MainTitleArea,
  C08CoursePickerGroup,
  C09Address,
  C10TabSection,
  C12Recommendation,
  C13BottomDock,
} from "@/components";
import { useAuth } from "@/store/authContext";
import { CourseShape } from "@/data/courses/courseTypes";
import useDetailPageData from "@/hooks/useDetailPageData";
import { ModalTypes, useApplicationInfo } from "@/store/applicationDataContext";
import { useUserInfo } from "@/store/userDataContext";
import { ApiItemTypeMapping } from "@/data/shared/entityShapes";
import { apiItemTypeMapping } from "@/utils/apiMapping";
import { navigateTo, switchTab } from "@/utils/navigation";
import { error } from "@/utils";
import { BottomDockButtonShape } from "@/components/c13-BottomDock";
import { ActionKeys, ActionNames, sendAction } from "@/utils/tracking";
import { useDidShow } from "@tarojs/taro";
import { useEventListSplit } from "@/hooks/useEventListSplit";
import style from "./index.module.scss";

export default function CourseDetail() {
  const { dispatchAuthAction } = useAuth();
  const { userInfoState } = useUserInfo();
  const { selectedCourseData } = userInfoState;
  const { dispatch } = useApplicationInfo();
  const [courseData, liked, preview] = useDetailPageData("course") as [
    CourseShape,
    Boolean,
    Boolean
  ];

  // For courses to populate sharing
  useEffect(() => {
    if (courseData) {
      dispatch({
        type: "SET_SHARE_DATA",
        data: {
          text: courseData.name,
          imagePath: courseData.sharePoster
            ? courseData.sharePoster
            : courseData.cover,
        },
      });
    }
  }, [courseData]);

  useDidShow(() => {
    sendAction(ActionNames.CourseDetailImpression, {
      [ActionKeys.CourseName]: courseData?.name,
      [ActionKeys.CourseType]: courseData?.type.toString(),
    });
  });
  const eventRecSplit = useEventListSplit(courseData);

  const [price, setPrice] = useState<number | string | null>(null);
  // API more flexible than design - simply picking the first scheduling
  const addressToDisplay = courseData?.schedulingList[0].address;

  const bookEvents = async () => {
    if (courseData && selectedCourseData) {
      const filteredSelectedCourseData = Object.values({
        ...selectedCourseData,
      }).map((sc) => {
        return {
          courseId: sc.courseId,
          scheduleId: sc.schedulingId,
        };
      });
      courseData.handlePlaceOrder({
        query: {
          type: ApiItemTypeMapping.Course,
          preOrderDetail: {
            mainId: courseData.id,
            count: 1,
            scheduleLings: filteredSelectedCourseData,
          },
          preOrderType: "buyNow",
        },
      });
      sendAction(ActionNames.CourseDetailCourseClick, {
        [ActionKeys.CourseName]: courseData.name,
        [ActionKeys.CourseType]: courseData.type.toString(),
        [ActionKeys.CourseDate]:
          Object.values(selectedCourseData)[0].schedulingDate,
        [ActionKeys.CourseLanguage]:
          Object.values(selectedCourseData)[0].languageName,
        [ActionKeys.CourseLocation]:
          courseData.schedulingList[0].address.courseAddress,
      });
    }
  };

  const bookIfTimeSelected = () => {
    // Only book if selection made for all parts
    if (
      Object.keys(selectedCourseData).length ===
      courseData.schedulingList.length
    ) {
      bookEvents();
    } else {
      error("请选择时间");
      // SCROLL to element
      setScrollToId(SCROLL_VIEW_ID);
      setTimeout(() => {
        setScrollToId(null);
      }, 1000);
    }
  };

  const lineUp = async () => {
    if (courseData) {
      const result = await courseData.handleLineUp({
        query: {
          mainId: courseData.id,
          type: ApiItemTypeMapping.Course,
        },
        authDispatch: dispatchAuthAction,
      });
      if (result) {
        navigateTo(`pages/user-waiting-list/index`);
      }
    }
  };

  const SCROLL_VIEW_ID = "SCROLL_TO_ELEMENT";
  const [scrollToId, setScrollToId] = useState<string | null>(null);

  const DEFAULT_PRIMARY_CTA_BOOK = {
    cb: bookIfTimeSelected,
    text: "立即预约",
  };
  const DEFAULT_SECONDARY_CTA_NULL = null;
  const GO_HOME = {
    cb: () => {
      switchTab("pages/home/index");
    },
    text: "其他课程",
  };
  const SHOW_QR_CODE = {
    cb: () => {
      dispatch({ type: "SHOW_MODAL", data: ModalTypes.QR });
    },
    text: "出示预约码",
  };

  const LINE_UP = {
    cb: lineUp,
    text: "候补登记",
  };

  const [primaryCta, setPrimaryCta] = useState<BottomDockButtonShape>(
    DEFAULT_PRIMARY_CTA_BOOK
  );
  const [secondaryCta, setSecondaryCta] =
    useState<BottomDockButtonShape | null>(DEFAULT_SECONDARY_CTA_NULL);

  useEffect(() => {
    if (courseData) {
      // Reset to defaults
      setPrimaryCta(DEFAULT_PRIMARY_CTA_BOOK);
      setSecondaryCta(DEFAULT_SECONDARY_CTA_NULL);

      // Does not exist
      if (courseData.isDeleted || !courseData.status) {
        setPrimaryCta(GO_HOME);
      } else {
        // No seats
        if (!courseData.totalSeatsLeftForAllScheduledCourses) {
          // Difficulties refactoring this section
          if (courseData.orderQuantityToBeWrittenOff === 0) {
            if (courseData.completedOrderQuantity! > 0) {
              setPrimaryCta(GO_HOME);
              setSecondaryCta(LINE_UP);
            } else {
              setPrimaryCta(LINE_UP);
            }
          } else {
            setPrimaryCta(SHOW_QR_CODE);
            setSecondaryCta(LINE_UP);
          }
        } else {
          // Seats available
          if (courseData.isAppointment) {
            setPrimaryCta(SHOW_QR_CODE);
            // Book with different text
            setSecondaryCta({
              cb: bookIfTimeSelected,
              text: "重新预约",
            });

            if (
              // Not sure if both these needed
              courseData.completedOrderQuantity! > 0 &&
              courseData.orderQuantityToBeWrittenOff === 0
            ) {
              setPrimaryCta(GO_HOME);
            }
          }
        }
      }
      setPrice(courseData.price);
    }

    // Update price
    if (Object.values(selectedCourseData).length) {
      setPrice(
        (Object.values(selectedCourseData)[0] &&
          Object.values(selectedCourseData)[0].price) ||
          0
      );
    }
  }, [courseData, selectedCourseData]);

  return (
    <Layout scrollIntoViewId={scrollToId}>
      <View className={style.wrapper}>
        {courseData && (
          <>
            {!!courseData?.carouselMap.length && (
              <C06HeroSlideBanner
                images={courseData.carouselMap}
                videoSrc={
                  courseData.mainPictureVideo
                    ? courseData.mainPictureVideo
                    : null
                }
                themeColor={courseData.typeLabelColor}
              />
            )}

            <WithMargins>
              <C07MainTitleArea
                categoryName={courseData.typeName}
                themeColor={courseData.typeLabelColor}
                price={price}
                heading={courseData.name}
                description={courseData.introduction}
              />

              <View id={SCROLL_VIEW_ID}>
                {courseData.schedulingList.map(
                  (courseSchedlingObj, courseSchedlingIdx) => {
                    const { courseId } = courseSchedlingObj;

                    return (
                      <C08CoursePickerGroup
                        key={courseSchedlingIdx}
                        eventData={courseSchedlingObj.schedulings.map(
                          (courseEventScheduling) => {
                            return {
                              courseId: courseId,
                              schedulingId: courseEventScheduling.schedulingId,
                              schedulingDate:
                                courseEventScheduling.schedulingDate,
                              languageName: courseEventScheduling.language,
                              schedulingStartTime:
                                courseEventScheduling.schedulingStartTime,
                              schedulingEndTime:
                                courseEventScheduling.schedulingEndTime,
                              remainingSeatCount:
                                courseEventScheduling.remainingSeatCount,
                              price: courseEventScheduling.price,
                            };
                          }
                        )}
                        combinedBookingId={`${courseData.id}-${courseId}`}
                        type="course"
                      />
                    );
                  }
                )}
              </View>

              {addressToDisplay && (
                <C09Address
                  upperLine={addressToDisplay.courseAddress}
                  lowerLine={addressToDisplay.courseAddressInfo}
                  lat={+addressToDisplay.lat}
                  lon={+addressToDisplay.lon}
                  dest={addressToDisplay.dest}
                />
              )}
            </WithMargins>

            {/* Tabbed view */}
            {courseData.courseInfo && (
              <C10TabSection tabContent={courseData.courseInfo} />
            )}

            {/* Recommended-events-slider */}
            {!!eventRecSplit.courses.length && (
              <C12Recommendation
                recommendationTitle="课程推荐"
                // Remap to not have changing types restrict too much
                cardData={eventRecSplit.courses.map((relatedEvent) => ({
                  cardId: relatedEvent.aboutId,
                  imagePath: relatedEvent.sharePoster || relatedEvent.cover,
                  title: relatedEvent.name,
                  tag: relatedEvent.typeName,
                  cost: relatedEvent.price,
                  type: "course-card",
                  themeColor: relatedEvent.labelColor,
                  redirect: apiItemTypeMapping[relatedEvent.typeCourse],
                }))}
              />
            )}

            {(!!courseData.shopRecommendations?.length ||
              !!eventRecSplit.otherEvents.length) && (
              <C12Recommendation
                recommendationTitle="您也可能喜欢"
                type="mixed"
                cardData={[
                  ...(courseData.shopRecommendations ?? []),
                  ...eventRecSplit.otherEvents,
                ].map((recommendItem) => ({
                  cardId: recommendItem.aboutId,
                  imagePath: recommendItem.sharePoster || recommendItem.cover,
                  title: recommendItem.name,
                  cost: recommendItem.price,
                  type: "recommendation-mixed",
                  themeColor: recommendItem.labelColor,
                  redirect: apiItemTypeMapping[recommendItem.typeCourse],
                }))}
              />
            )}
          </>
        )}
      </View>
      {courseData && !preview && (
        <C13BottomDock
          onPrimaryClick={primaryCta}
          onSecondaryClick={secondaryCta}
          onSaveClick={() => {
            courseData.handleFav(courseData!.id, courseData!.type);
          }}
          hex={courseData.typeLabelColor}
          liked={liked ? true : false}
        />
      )}
    </Layout>
  );
}
